# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pickle
import redis
import logging

LOGGER = logging.getLogger(__name__)

"""
class AquilaPipeline(object):
    collection_name = 'holding_area'

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
        )

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        LOGGER.debug('Crawled item {0}'.format(dict(item)))
        self.db[self.collection_name].insert_one(dict(item))
        return item

"""


class AquilaPipeline(object):
    def __init__(self, redis_host, redis_port, redis_db, redis_key):
        self.redis_host = redis_host
        self.redis_port = redis_port
        self.redis_db = redis_db
        self.redis_key = redis_key

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            redis_host=crawler.settings.get('REDIS_HOST'),
            redis_port=crawler.settings.get('REDIS_PORT'),
            redis_db=crawler.settings.get('REDIS_DB'),
            redis_key=crawler.settings.get('REDIS_KEY')
        )

    def open_spider(self, spider):
        self.db = redis.Redis(host=self.redis_host, port=self.redis_port,
                              db=self.redis_db)

    def process_item(self, item, spider):
        LOGGER.debug('Crawled item {0}'.format(dict(item)))
        data = pickle.dumps(dict(item))
        self.db.lpush(self.redis_key, data)
        return item
